<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form class="antd-modal-form" v-bind="formItemLayout" ref="formRef" name="GbtIntegralVoteForm">
          <a-row>
						<a-col :span="24">
							<a-form-item label="名称" v-bind="validateInfos.name" id="GbtIntegralVote-name" name="name">
                <JSearchSelect
                  v-model:value="formData.name"
                  placeholder="请输入名字"
                  dict="gbt_integral_user,name,id"
                  async
                  allow-clear
                  @change="onUserChange"
                />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="用户id" v-bind="validateInfos.userid" id="GbtIntegralVote-userid" name="userid">
								<a-input v-model:value="formData.userid" placeholder="请输入用户id"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="一级部门" v-bind="validateInfos.firstDept" id="GbtIntegralVote-firstDept" name="firstDept">
								<a-input v-model:value="formData.firstDept" placeholder="请输入一级部门"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="二级部门" v-bind="validateInfos.secondDept" id="GbtIntegralVote-secondDept" name="secondDept">
								<a-input v-model:value="formData.secondDept" placeholder="请输入二级部门"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="岗位" v-bind="validateInfos.title" id="GbtIntegralVote-title" name="title">
								<a-input v-model:value="formData.title" placeholder="请输入岗位"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="评选类型" v-bind="validateInfos.voteType" id="GbtIntegralVote-voteType" name="voteType">
								<j-dict-select-tag v-model:value="formData.voteType" dictCode="vote_type" placeholder="请选择评选类型"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="理由" v-bind="validateInfos.reason" id="GbtIntegralVote-reason" name="reason">
								<j-editor v-model:value="formData.reason"  :autoFocus="false"/>
							</a-form-item>
						</a-col>
						<!-- <a-col :span="24">
							<a-form-item label="票数" v-bind="validateInfos.votes" id="GbtIntegralVote-votes" name="votes">
								<a-input-number v-model:value="formData.votes" placeholder="请输入票数" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="普通投票" v-bind="validateInfos.normalVote" id="GbtIntegralVote-normalVote" name="normalVote">
								<a-input-number v-model:value="formData.normalVote" placeholder="请输入普通投票" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="委员会投票" v-bind="validateInfos.vipVote" id="GbtIntegralVote-vipVote" name="vipVote">
								<a-input-number v-model:value="formData.vipVote" placeholder="请输入委员会投票" style="width: 100%" />
							</a-form-item>
						</a-col> -->
						<!-- <a-col :span="24">
							<a-form-item label="期数" v-bind="validateInfos.period" id="GbtIntegralVote-period" name="period">
								<a-input v-model:value="formData.period" placeholder="请输入期数"  allow-clear ></a-input>
							</a-form-item>
						</a-col> -->
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, onMounted, inject, defineProps, unref } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JEditor from '/@/components/Form/src/jeecg/components/JEditor.vue';
  import { getValueType } from '/@/utils';
  import { gbtIntegralVoteSaveOrUpdate } from '../GbtIntegralVoteInfo.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
import { getUser } from '../../integralRecord/GbtIntegralRecord.api';
import { JSearchSelect } from '/@/components/Form';


  //接收主表id
  const mainId = inject('mainId');
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
        name: '',   
        userid: '',   
        firstDept: '',   
        secondDept: '',   
        title: '',   
        voteType: '',   
        reason: '',   
        votes: undefined,
        normalVote: undefined,
        vipVote: undefined,
        period: '',   
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    name: [{ required: true, message: '请输入名称!'},],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  const props = defineProps({
    disabled: { type: Boolean, default: false },
  });
  const formItemLayout = {
    labelCol: { xs: { span: 24 }, sm: { span: 5 } },
    wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
  };
  

  
// 选中用户时触发，可以同步其他表单字段，比如部门
const onUserChange = (userid, option) => {
  // option.extra 就是完整用户数据
  getUser({ id: userid })
    .then((user) => {
      formData.name = user.name;
      formData.userid = user.userid;
      formData.firstDept = user.firstDept;
      formData.secondDept = user.secondDept;
      formData.title = user.title;
    })
    .catch((err) => {
      console.error('获取用户详情失败', err);
    });
};

  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData,tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
   
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    if (unref(mainId)) {
      model['infoId'] = unref(mainId);
    }
    await gbtIntegralVoteSaveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
